<template>
  <div class="relevance-box">
    <flexbox
      v-if="!disabled"
      class="handel-header">
      <div class="desc text-one-line"><span v-if="showTips">注：仅支持修改在当前客户下维护的关系，如需修改其他客户关系请到对应客户详情下修改</span></div>
      <div>
        <crm-relative
          v-if="showSelectView"
          ref="crmrelative"
          :visible.sync="showSelectView"
          :radio="false"
          :selected-data="selectedData"
          data-type="customer"
          @changeCheckout="selectInfos" />
        <el-button
          type="primary"
          @click="addClick">添加</el-button>
      </div>
    </flexbox>
    <el-table
      :data="list"
      max-height="300px"
      style="width: 100%;">
      <el-table-column
        v-if="sourceShow"
        prop="sourceCustomerName"
        min-width="90px"
        show-overflow-tooltip
        label="客户名称" />
      <el-table-column
        width="150px"
        label="客户关系">
        <template slot-scope="{row}">
          <el-cascader
            v-model="row.relationsId"
            :disabled="disabled || (!!id && id !== row.sourceCustomerId)"
            style="width: 100%;"
            :options="relationsOptions"
            :props="{ value: 'id', label: 'name', emitPath: false }"
            :show-all-levels="false"
            @change="relationsChange($event, row)" />
        </template>
      </el-table-column>
      <el-table-column
        prop="targetCustomerName"
        show-overflow-tooltip
        min-width="90px"
        label="客户名称" />
      <el-table-column
        v-if="!disabled"
        fixed="right"
        width="70px"
        label="操作">
        <template slot-scope="scope">
          <el-button
            :disabled="!!id && id !== scope.row.sourceCustomerId"
            type="primary-text"
            style="padding: 0;"
            @click="deleteItemClick(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script type="text/javascript">
import { crmCustomerRelationsConfigQueryTreeListAPI } from '@/api/admin/crm'
import { crmCustomerReadAPI } from '@/api/crm/customer'
import CrmRelative from '@/components/CreateCom/CrmRelative'

import { objDeepCopy } from '@/utils'

export default {
  name: 'RelevanceEnterprise', // 关联客户关系
  components: {
    CrmRelative
  },
  props: {
    showTips: {
      type: Boolean,
      default: false
    },
    id: [String, Number], // 无 id 是新建，有id 是编辑
    disabled: {
      type: Boolean,
      default: false
    },
    // 已有数据
    value: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      loading: false,

      // 客户关系选项
      relationsOptions: [],
      list: [],
      showSelectView: false, // 内容
      selectedData: { customer: [] },
      customerDetail: null // 客户详情
    }
  },
  computed: {
    // 仅编辑展示
    sourceShow() {
      return !!this.id
    }
  },
  watch: {
    list: {
      handler() {
        this.updateValue()
      },
      deep: true
    }
  },
  created() {
    const list = objDeepCopy(this.value || [])
    this.list = list
    // relationsType（1：新建客户关联，2：图谱客户）

    this.getCustomerDetail()
    this.getRelationsOptions()
  },
  methods: {
    /**
     * @description: 根据id 获取当前客户详情
     * @return {*}
     */
    getCustomerDetail() {
      if (!this.id) return

      crmCustomerReadAPI({
        customerId: this.id
      })
        .then(res => {
          this.customerDetail = res.data
        })
        .catch(() => {
        })
    },

    /**
     * @description: 获取客户关系选项
     * @return {*}
     */
    getRelationsOptions() {
      crmCustomerRelationsConfigQueryTreeListAPI()
        .then(res => {
          this.relationsOptions = res.data
        })
        .catch(() => {})
    },

    /**
     * @description: 客户关系改变
     * @param {*} val
     * @param {*} data
     * @return {*}
     */
    relationsChange(val, data) {
      this.relationsOptions.forEach(item => {
        item.children.forEach(subItem => {
          if (subItem.id == val) {
            data.relationsName = subItem.name
          }
        })
      })
    },

    /**
     * @description: 选中
     * @param {*} data
     * @return {*}
     */
    selectInfos(data) {
      const selectedData = data.data
      if (selectedData) {
        const selectedIds = this.list.map(item => item.targetCustomerId)

        selectedData.forEach(element => {
          if (!selectedIds.includes(element.customerId)) {
            this.list.push({
              sourceCustomerName: this.customerDetail?.customerName || '',
              sourceCustomerId: this.customerDetail?.customerId || '',
              relationsId: '',
              relationsName: '',
              relationsType: 2, // 1：新建客户关联(旧数据)，2：图谱客户
              targetCustomerId: element.customerId,
              targetCustomerName: element.customerName
            })
          }
        })
      }
    },

    /**
     * @description: 添加
     * @return {*}
     */
    addClick() {
      this.selectedData = { customer: this.list.map(item => {
        return {
          customerId: item.targetCustomerId,
          customerName: item.targetCustomerName
        }
      }) }
      this.showSelectView = true
    },

    /**
     * @description: 删除
     * @param {*} index
     * @return {*}
     */
    deleteItemClick(index) {
      this.list.splice(index, 1)
    },

    /**
     * @description: 更新值
     * @return {*}
     */
    updateValue() {
      this.$emit('input', this.list)
    }
  }
}
</script>
<style lang="scss" scoped>
.relevance-box {
  .handel-header {
    .desc {
      flex: 1;
      color: $--color-text-secondary;
    }
  }

  ::v-deep .el-table {
    margin-top: 8px;

    .el-table__body {
      width: 100% !important;
    }
  }
}

</style>
